<template>
  <div class="product-detail-container">
    <div class="product-content" v-if="product">
      <div class="product-gallery">
        <el-button
          class="back-button"
          @click="router.back()"
          type="primary"
          circle
          >返回商品列表
        </el-button>
        <el-image
          :src="product.picture"
          :alt="product.title"
          fit="contain"
          class="main-image"
          loading="lazy"
          :preview-teleported="true"
        />
      </div>

      <div class="product-info">
        <h1 class="product-title">{{ product.title }}</h1>
        <div class="product-name" style="font-size: 60px; color: #ff6700">
          <span>{{ product.name }}</span>
        </div>
        <div class="product-desc">
          <h2 style="font-size: 30px; color: #333; margin-top: 15px">
            产品介绍:
          </h2>
          <el-card
            shadow="never"
            class="desc-card"
            style="font-size: 40px; color: #666"
          >
            {{ product.description }}
          </el-card>
        </div>
        <div
          class="product-price"
          style="font-size: 40px; color: #ff6700; margin-top: 20px"
        >
          <span class="label">单价：</span>
          <span class="currency">¥</span>
          <span class="amount">{{ product.price }}</span>
        </div>
        <div class="product-actions">
          <el-input-number
            v-model="quantity"
            :min="1"
            :max="99"
            size="large"
            class="quantity-input"
            controls-position="left"
          />
          <el-button
            type="primary"
            size="large"
            class="cart-btn"
            @click="checkLoginAndAddToCart"
          >
            <el-icon><ShoppingCart /></el-icon>
            加入购物车
          </el-button>
          <el-button type="danger" size="large" class="buy-btn" @click="buyNow">
            立即购买
          </el-button>
        </div>
      </div>
    </div>

    <div v-else class="loading-state">
      <el-empty description="商品信息加载中...">
        <template #image>
          <el-icon><Loading /></el-icon>
        </template>
      </el-empty>
    </div>
  </div>
</template>
  
  <script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getGoods } from "../../api/api";
import config from "../../config";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";

const route = useRoute();
const router = useRouter();
const product = ref(null);
const quantity = ref(1);

onMounted(async () => {
  try {
    const response = await getGoods({ id: route.params.id });
    console.log(response);
    if (response != null) {
      product.value = {
        ...response,
        picture: config.baseURL + response.picture,
        description: removeTags(response.description),
      };
      console.log(product.value);
    }
  } catch (error) {
    console.error("Failed to load product details:", error);
  }
});

const removeTags = (str) => {
  return str.replace(/<[^>]+>/g, "");
};

const checkLoginAndAddToCart = () => {
  const userName = localStorage.getItem('userName');
  if (!userName) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  addToCart();
};

const addToCart = () => {
  if (!product.value) {
    ElMessage.error("商品信息不存在");
    return;
  }

  // 从localStorage获取现有购物车数据
  let cart = JSON.parse(localStorage.getItem("cart") || "[]");
  console.log(cart);
  // 检查商品是否已在购物车中
  const existingItem = cart.find((item) => item.id === product.value.id);

  if (existingItem) {
    // 如果商品已存在,增加数量
    existingItem.quantity += quantity.value;
  } else {
    // 如果商品不存在,添加新商品
    cart.push({
      id: product.value.id,
      title: product.value.title,
      price: product.value.price,
      picture: product.value.picture,
      quantity: quantity.value,
    });
  }

  // 保存更新后的购物车数据
  localStorage.setItem("cart", JSON.stringify(cart));

  ElMessage.success("已添加到购物车");
  router.go(0);
};

const buyNow = () => {
  // 实现立即购买逻辑
  router.push("/cart");
};
</script>
  
  <style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
}

.product-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  margin-top: 20px;
}

.product-gallery {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  position: relative; /* 添加这行 */
}

/* 添加返回按钮样式 */
.back-button {
  position: absolute;
  top: 0px;
  left: 20px;
  z-index: 1;
  border-radius: 4px !important; /* Override circle button style */
  width: 120px;
  height: 40px;
}

.main-image {
  max-width: 100%;
  height: auto;
}

.product-info {
  padding: 20px;
}

.desc-card {
  background-color: #f5f5f5;
}

.product-info h1 {
  margin: 0 0 20px 0;
  font-size: 24px;
}

.product-price {
  font-size: 28px;
  color: #ff6700;
  margin-bottom: 20px;
}

.product-desc {
  color: #666;
  line-height: 1.6;
  margin-bottom: 30px;
}

.product-actions {
  display: flex;
  gap: 20px;
  align-items: center;
}

.quantity-input {
  width: 120px;
}

@media (max-width: 768px) {
  .product-content {
    grid-template-columns: 1fr;
  }
}
</style>